package com.dz.handler;

import com.dz.exception.BaseException;
import com.dz.exception.SystemException;
import com.dz.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     */
    @ExceptionHandler
    public Result<?> exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    public Result<?> systemExceptionHandler(SystemException e) {
        // 打印异常信息
        log.error("出现了异常: {}",e.getMsg());
        // 从异常对象中获取提示信息封装返回
        return Result.error(e.getMsg());
    }

    @ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public Result<?> validationExceptionHandler(Exception e) {
        // 打印异常信息
        log.error("出现了异常....",e);
        // 从异常对象中获取提示信息封装返回
        return Result.error(e.getMessage());
    }
}
